var prifix = '';


var RESERVATIONCENTERURL = {                                                        //预约中心

    addReservation: {                                                                //添加预约
        store: prifix + '/reserve/store',
    },
    reservationList: {                                                              //预约列表页面
        index: prifix + '/reserve/index',                                         //预约列表
        edit: prifix + '/reserve/edit',
        update: prifix + '/reserve/update',                                      //更新诊室
        destroy: prifix + '/reserve/destroy',                                      //解除预约
        notify: prifix + '/reserve/notify'                                        //发送短信
    },
    statistical: {                                                                   //统计页面
        doctor: {                                                                    //医生统计页面
            statistics: prifix + '/reserve/statistics/situation'                    //查询图表信息
        },
        admin: {
            visit: prifix + '/reserve/statistics/visit'
        }


    },
    doctorManagement: {                                                              //医生管理
        doctor: {                                                                    //医生页面
            store: prifix + '/reserve/schedule/store',
            update: prifix + '/reserve/schedule/update',
            plan: prifix + '/reserve/schedule/plan',
            planOfMonth: prifix + '/reserve/schedule/planOfMonth',
            storeWithAMonth: prifix + '/reserve/schedule/storeWithAMonth',
            destroyMonth: prifix + '/reserve/schedule/destroyMonth',
            planInMonthAfterNow: prifix + '/reserve/schedule/planInMonthAfterNow'
        },
        admin: {                                                                     //管理员页面
            index: prifix + '/manage/doctor',
            store: prifix + '/manage/doctor/store',
            update: prifix + '/manage/doctor/update',
            destroy: prifix + '/manage/doctor/destroy',
            edit: prifix + '/manage/doctor/edit'
        }
    },
    patientPool: {
        doctor: {                                                                    //医生用户
            index: prifix + '/reserve/pool/index',
            reject: prifix + '/reserve/pool/reject',
            accept: prifix + '/reserve/pool/accept'
        },
        admin: {
            assignTo: prifix + '/reserve/pool/assignTo',
            doctors: prifix + '/reserve/pool/doctors'
        }
    },
    messageCenter: {
        index: prifix + '/reserve/message',
        unread: prifix + '/reserve/message/unread'
    }

};


//confirm 弹窗  start
function confirmModel(title, body, okBtn, cancelBtn, okHidden) {
    if (!title) {
        title = '温馨提示';
    }
    if (!body) {
        body = '确定要删除吗？';
    }
    if (!okBtn) {
        okBtn = '确定';
    }
    if (!cancelBtn) {
        cancelBtn = '取消';
    }
    $.confirm({
        title: title,
        body: body,
        okBtn: okBtn,
        cancelBtn: cancelBtn,
        transition: true,
        okHidden: function () {
            okHidden();
        }
    });
}

//confirm 弹窗  end

//alert 弹窗  start
function alertModel(title, body) {
    if (!title) {
        title = '温馨提示';
    }
    if (!body) {
        body = '出错了，再来一次！';
    }
    $.alert({
        title: title,
        body: body,
        transition: true
    });
}

//alert 弹窗  end

// ajax 请求 start
function ajaxGet(url, data, success, error) {
    $.ajax({
        type: "get",
        url: url,
        data: data,
        dataType: "json",
        beforeSend: function () {
            $('.loading').removeClass('display-none');
        },
        success: function (data) {
            $('.loading').addClass('display-none');
            if (typeof data == 'string') {
                data = $.parseJSON(data);
            }
            success(data);
        },
        error: function (x, t, e) {
            $('.loading').addClass('display-none');
            if (error === undefined) {
                if (t == 'timeout') {
                    // console.log('请求超时');
                }
            } else {
                error(x, t, e);
            }

        }
    });
}

function ajaxPost(url, data, success, error) {
    $.ajax({
        type: "post",
        url: url,
        data: data,
        dataType: "json",
        beforeSend: function () {
            $('.loading').removeClass('display-none');
        },
        success: function (data) {
            $('.loading').addClass('display-none');
            if (typeof data == 'string') {
                data = $.parseJSON(data);
            }
            success(data);
        },
        error: function (x, t, e) {
            $('.loading').addClass('display-none');
            if (error === undefined) {
                if (t == 'timeout') {
                    // console.log('请求超时');
                }
            } else {
                error(x, t, e);
            }

        }
    });
}

// ajax 请求 end

// 页码函数方法  start
function page(id, data, fun, param) {
    var totalPages = Math.ceil(data.pagination.total / data.pagination.per_page);
    $('#' + id).jqPaginator({
        totalPages: totalPages,
        visiblePages: 5,
        currentPage: data.pagination.current_page,
        first: '',
        last: '',
        onPageChange: function (e) {
            param.page = e;
            fun(param);
        }
    })
}

// 页码函数方法  end

// 日历限制最小(大)可选日期为当日  start
var date = new Date();

function formatDate(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + m + '-' + d;
};
$('.limitStartData').datepicker({
    startDate: formatDate(date)
});
$('.limitEndData').datepicker({
    endDate: formatDate(date)
});
// 日历限制最小(大)可选日期为当日  end

//对一个日期相加（减）天数计算 方法  start
function addDate(date, days) {
    var d = new Date(date);
    d.setDate(d.getDate() + days);
    var month = d.getMonth() + 1;
    var day = d.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    var val = d.getFullYear() + "-" + month + "-" + day;
    return val;
}

//对一个日期相加（减）天数计算 方法  end

//将系统日期变为 yyyy-mm-dd h:m:s   格式   start
function formatTen(num) {
    return num > 9 ? (num + "") : ("0" + num);
}

function formatDate(date, h, m, s) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    var time = year + "-" + formatTen(month) + "-" + formatTen(day);
    if (h) {
        time += ' ' + hour;
        if (m) {
            time += ':' + minute;
            if (s) {
                time += ':' + second;
            }
        }
    }
    return time
}

//将系统日期变为 yyyy-mm-dd h:m:s   格式   end

//获取日期对应星期几  start
function getWeek(data) {
    var weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    var week = weekArr[new Date(data).getDay()];
    return week;
}

//获取日期对应星期几  end

//模态框 层上层提示点击周围关闭层  start
$('body').delegate('div.alertZindex', 'click', function () {
    $('.sui-modal-backdrop').removeClass('alertZindex');
});
//模态框 层上层提示点击周围关闭层  end

//ie 低版本  maxLength 属性  start
$('body').find('textarea').change(function () {
    var len = $(this).attr('maxLength');
    var val = $(this).val();
    $(this).val(val.substring(0, len));
});
$('body').find('input').change(function () {
    var len = $(this).attr('maxLength');
    var val = $(this).val();
    $(this).val(val.substring(0, len));
});
//ie 低版本  maxLength 属性  end


//姓名复选框是否全选 start   todo 通用于预约中心和医生管理
$('.reservationCenter-table thead th input.checkBox').click(function () {
    var inputList = $('#' + $(this).attr('data-id')).find('td input.checkBox');
    if ($(this).is(':checked')) {
        for (var i = 0; i < inputList.length; i++) {
            if (!($(inputList[i]).is('checked'))) {
                if (!($(inputList[i]).attr('disabled'))) {
                    $(inputList[i]).attr('checked', 'checked');
                    $(inputList[i]).prop('checked', true);
                }
            }
        }
    } else {
        for (var j = 0; j < inputList.length; j++) {
            $(inputList[j]).removeAttr('checked');
        }
    }
});
$('.reservationCenter-table tbody').delegate('td input.checkBox', 'click', function () {
    var inputList = $(this).parent().parent().parent().parent().find('td input:checkBox');
    var dataId = $(this).parent().parent().parent().parent().attr('id');
    var dataIdInput = $('.reservationCenter-table thead input[data-id="' + dataId + '"]');
    if ($(this).is(':checked')) {
        var checked = true;
        for (var i = 0; i < inputList.length; i++) {
            if (!($(inputList[i]).attr('disabled'))) {
                if (!($(inputList[i]).is(':checked'))) {
                    checked = false;
                    break;
                    return;
                }
            }
        }
        if (checked) {
            dataIdInput.attr('checked', 'checked');
            dataIdInput.prop('checked', true);
        }
    } else {
        dataIdInput.removeAttr('checked');
    }
});
//姓名复选框是否全选 end


//手机号11位 且 符合规则 监测  start
$('input.phoneLength').bind('input.phoneLength propertychange', function () {
    var reg = /^\d+$/;
    if ($(this).val().length > 11) {
        $(this).val($(this).val().slice(0, 11));
    } else {
        if (!(reg.test($(this).val()))) {
            $(this).val($(this).val().slice(0, $(this).val().length - 1));
        }
    }
});

function checkPhone(val) {
    var reg = /^1[345789]{1}\d{9}$/;
    if (val) {
        val = val.trim();
        if (reg.test(val)) {
            return true;
        }
        else {
            return false;
        }
    }
    else {
        return true;
    }
}

//手机号11位 且 符合规则 监测  end

//姓名 16个字符监测  start
function chkstrlen(str) {
    var strlen = 0;
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 255) //如果是汉字，则字符串长度加2
            strlen += 2;
        else
            strlen++;
    }
    return strlen;
}

function checkName(nameStr) {
    var reg = /^([\u4E00-\uFA29]*[0-9]*[a-z]*[A-Z]*)+$/;
    if (nameStr) {
        nameStr = nameStr.trim();
        if ((reg.test(nameStr)) && (chkstrlen(nameStr))) {
            return true;
        }
        else {
            return false;
        }
    }
    else {
        return true;
    }
}

//姓名 16个字符监测  end

//密码  6-16位数字 字母  或者两者组合  start
function checkPassword(pwd) {
    var reg = /^[A-Za-z0-9]{6,16}$/;
    if (reg.test(pwd)) {
        return true;
    } else {
        return false;
    }
}

//密码  6-16位数字 字母  或者两者组合  end

// 检测两个时间大小 (第三个参数没有 默认 结束时间大于开始时间)  start
function checkTwoDate(star_time, end_time, endLessStart) {
    var now = new Date();
    if (star_time && end_time) {
        // 结束时间
        var edate = end_time.split('-');
        var end = new Date(edate[0], edate[1] - 1, edate[2]);
        // 开始时间
        var sdate = star_time.split('-');
        var start = new Date(sdate[0], sdate[1] - 1, sdate[2]);
        if (endLessStart) {
            if (end - start <= 0) {
                return true;
            } else {
                return false;
            }
        } else {
            if (end - start >= 0) {
                return true;
            } else {
                return false;
            }
        }
    } else {
        return true;
    }
}

// 检测两个时间大小 (第三个参数没有 默认 结束时间大于开始时间)  end


//数字 最小 最大 且保留几位小数方法 start
function dealNum(_this, min, Min, max, Max, fix) {
    var num = parseFloat(_this.val());
    if (isNaN(num)) {
        _this.val('');
    } else {
        if (num <= min) {
            _this.val(Min);
        } else if (num > max) {
            _this.val(Max);
        } else {
            _this.val(parseFloat(parseFloat(num).toFixed(fix)));
        }
    }
}

//数字 最小 最大 且保留几位小数方法 end

//人数类型 1-999 输入框限制  start
$('body').delegate('.peopleInput', 'blur', function () {
    dealNum($(this), 1, 1, 999, 999, 0);
});
//人数类型 1-999 输入框限制  end


//列表页面  查询按钮  start
$('#listQueryBtn').click(function () {
    var params = getSearchParams($(this));
    if (params) {
        getReservationList(params);
    }
});
//列表页面  查询按钮  end

//预约列表 获取数据 方法  start
function getReservationList(result) {
    ajaxGet(RESERVATIONCENTERURL.reservationList.index, result, function (data) {
        if (data.code === 10000) {
            var str = '';
            for (var i = 0; i < data.data.length; i++) {

                str += ' <tr data-reservationId="' + data.data[i].id + '" data-status="' + data.data[i].status.key + '">' +
                    '<td><lable><input type="checkbox" class="checkBox" data-patientId="' + data.data[i].patient_id + '">' + (i + 1) + '</lable></td>' +
                    '<td>' + data.data[i].patient.name + '</td>' +
                    '<td>' + data.data[i].patient.sex.value + '</td><td>' + data.data[i].patient.age + '</td>' +
                    '<td>' + data.data[i].patient.phone + '</td>' +
                    '<td>' + data.data[i].time + ' ' + data.data[i].section + '</td>' +
                    '<td>' + data.data[i].doctor.name + '</td>' +
                    '<td><span class="clinic">' + data.data[i].room + '</span>诊室</td>' +
                    '<td class="statusText">' + data.data[i].status.value + '</td>' +
                    '<td>' +
                    '<span class="btn btn-outline btn-primary margin-right-5 viewCase" data-patient-id="' + data.data[i].patient.id + '">查看病历</span>' +
                    '<span class="btn btn-outline btn-warning margin-right-5 addSubsequent" data-patient-id="' + data.data[i].patient.id + '">添加复诊</span>' +
                    '</td></tr>'
            }
            $('#reservationListBody').html(str);
            // 页码
            if (data.meta.pagination.total_pages > 1) {
                page('listPager', data.meta, getReservationList, result);
            } else {
                $('#listPager').html('');
            }
            $('#reservationCenterNav li[data-page="reservationList"]').attr('data-load', 'yes');//改变标签栏状态
        } else if (data.code === 40100) {
            aClick();
        } else if (String(data.code) === '40001') {
            $('#reservationListBody').html('<tr><td colspan="10">暂无数据</td></tr>');
            $('#listPager').html('');
        } else {
            alertModel('', '获取失败，' + data.message);
        }
    }, function (x, t, e) {
    })
};
//预约列表 获取数据 方法  end

//操作栏  所有点击按钮  获取要修改的预约 ID  start
function getReservationId(tableId, status) {
    var patientArr = [];
    var inputCheckBox = $('#' + tableId).find('td input.checkBox');

    for (var i = 0; i < inputCheckBox.length; i++) {
        var tr = $(inputCheckBox[i]).parent().parent().parent();
        var condition = status ? (tr.attr('data-status') !== status) : true;
        if ($(inputCheckBox[i]).is(':checked') && condition) {
            patientArr.push(tr.attr('data-reservationId'));
        }
    }
    return patientArr;
};
//操作栏  所有点击按钮  获取要修改的预约 ID  end

//添加预约  start
$('#listOperationBtnBox .addReservationBtn').click(function () {
    window.location.href = $(this).attr('data-url');
});
//添加预约  end

//修改诊室  点击  start
$('#listOperationBtnBox .editClinicBtn').click(function () {
    var reservationIdArr = getReservationId('reservationListBody');
    if (reservationIdArr.length) {
        $('#editClinic').modal('show');  //打开修改诊室模态框
        $('#editClinicSaveBtn').attr('data-reservationIdArr', reservationIdArr);
        $('#editClinicSaveBtn').attr('data-tableId', 'reservationListBody');
    } else {
        alertModel('', '请先选择患者！');
    }
});
//修改诊室  点击  end

//解除预约  点击  start
$('#listOperationBtnBox .removeReservationBtn').click(function () {
    var reservationIdArr = getReservationId('reservationListBody', 2);
    if (reservationIdArr.length) {
        confirmModel('', '确定要解除吗？', '', '', function () {
            ajaxPost(RESERVATIONCENTERURL.reservationList.destroy, {ids: reservationIdArr}, function (data) {
                if (data.code == 10000) {
                    for (var i = 0; i < reservationIdArr.length; i++) {
                        $('#reservationListBody').find('tr[data-reservationId="' + reservationIdArr[i] + '"]').remove();
                    }
                    alertModel('', '解除成功！');
                } else if (data.code === 40100) {
                    aClick();
                } else {
                    alertModel('', '解除失败，' + data.message);
                }
            }, function () {
            })
        });
    } else {
        alertModel('', '请先选择患者！');
    }
});
//解除预约  点击  end

//推送消息和发送短信  点击  和 发送请求  start
$('#listOperationBtnBox .sendAppMessageBtn').click(function () {
    var reservationIdArr = getReservationId('reservationListBody');
    if (reservationIdArr.length) {
        sendMessage(url, reservationIdArr);
    } else {
        alertModel('', '请先选择患者！');
    }
});
$('#listOperationBtnBox .sendPhoneMessageBtn').click(function () {
    var reservationIdArr = getReservationId('reservationListBody', 1);
    if (reservationIdArr.length) {
        sendMessage(RESERVATIONCENTERURL.reservationList.notify, reservationIdArr);
    } else {
        alertModel('', '请先选择患者！');
    }
});

function sendMessage(url, reservationIdArr) {
    confirmModel('', '确定要发送吗？', '', '', function () {
        ajaxPost(url, {ids: reservationIdArr}, function (data) {
            if (data.code == 10000) {
                var body = $('#reservationListBody');
                $.each(reservationIdArr, function (i, v) {
                    body.find('tr[data-reservationid=' + v + ']').find('td.statusText').html('已发送');
                });
                alertModel('', '发送成功！');
            } else if (data.code === 40100) {
                aClick();
            } else {
                alertModel('', '发送失败，' + data.message);
            }
        }, function () {
        })
    });
};
//推送消息和发送短信  点击  和 发送请求  end

//修改诊室弹出框   保存点击  start
$('#editClinicSaveBtn').click(function () {
    var reservationIdArr = $(this).attr('data-reservationIdArr').split(',');
    for (var j = 0; j < reservationIdArr.length; j++) {
        reservationIdArr[j] = parseInt(reservationIdArr[j]);
    }
    var room = $(this).parent().prev().find('select').val();
    $(this).prev().click();  //关闭模态框
    ajaxPost(RESERVATIONCENTERURL.reservationList.update, {ids: reservationIdArr, room: room}, function (data) {
        if (data.code == 10000) {
            for (var i = 0; i < reservationIdArr.length; i++) {
                $('#reservationListBody').find('tr[data-reservationId="' + reservationIdArr[i] + '"] td span.clinic').html(room);
            }
            alertModel('', '修改成功！');
        } else if (data.code === 40100) {
            aClick();
        } else {
            alertModel('', '修改失败，' + data.message);
        }
    }, function () {
    });
});
//修改诊室弹出框   保存点击  end

//查看病历按钮  点击 start
$('#reservationListBody').delegate('td span.viewCase', 'click', function () {
    var id = $(this).attr('data-patient-id');

    $.get('/manage/record/list/' + id, function (data) {
        if (data.code === 40100) {
            aClick()
        } else {
            var str = '';
            $.each(data, function (i, v) {
                str += '<option value="' + v.id + '">' + v.visit_type.value + v.clinic_at + '</option>';
            });
            $('#witch_record').html(str).change();
            $('#viewCaseModal').modal('show');
        }

    }, 'json');
})
// 添加复诊 点击按钮  start
    .delegate('.addSubsequent', 'click', function () {
        var patientId = $(this).attr('data-patient-id');   //获取病人id
        sessionStorage.removeItem('tabPage');
        sessionStorage.removeItem('record_id');
        sessionStorage.setItem('patient_id', patientId);
        window.location.href = '/manage/subsequent';
    });
//  病历选择后的change事件
$('#witch_record').change(function () {
    $.get('/manage/record/print/show', {record_id: $(this).val()}, function (data) {
        $('#viewCaseModal').find('.modal-body').html(data);
    }, 'html');
});

//查看病历按钮  点击 end

//获取查询搜索条件方法  start   todo 患者池和预约列表通用
function getSearchParams(_this) {
    var serializeArr = $('#' + _this.attr('data-id')).find('div.dataSerialize');
    var params = {}; //存储查询时需要提交的数据
    for (var i = 0; i < serializeArr.length; i++) {
        var keyname = '';
        if ($(serializeArr[i]).find('.form-control').length === 1) {
            keyname = $(serializeArr[i]).find('.form-control').attr('name');
            params[keyname] = $(serializeArr[i]).find('.form-control').val();
        } else {
            params[$(serializeArr[i]).find('.form-control').attr('data-name')] = [];
            var inputArr = $(serializeArr[i]).find('.form-control');
            for (var j = 0; j < inputArr.length; j++) {
                params[$(serializeArr[i]).find('.form-control').attr('data-name')].push($(inputArr[j]).val());
            }
            if (!params.times[0]) {
                params.times[0] = formatDate(new Date());
                $('#' + _this.attr('data-id') + ' input[name="start_time"]').val(params.times[0]);
            }
        }
    }
    ;
    params.page = 1;  //页码为1
    if (checkName(params.name)) {
        if (checkPhone(params.phone)) {
            if (checkTwoDate(params.times[0], params.times[1])) {
                return params;
            } else {
                alertModel('', '开始时间要早于结束时间！');
                return false;
            }
        } else {
            alertModel('', '请输入正确的手机号！');
            return false;
        }
    } else {
        alertModel('', '姓名长度不能超过16个字符！');
        return false;
    }
};
//获取查询搜索条件方法  end


//***************************医生操作页面  start***************************

//添加预约 方块 点击  start
$('.userStatistics .addReservationBox').click(function () {
    window.location.href = $(this).attr('data-url');
});
//添加预约 方块 点击  end

//医生统计 查看预约信息  start
$('#statistical .viewReservation').click(function () {
    $('#adminViewReservation').modal('show');
    var doctor_id = $('#reservationList .searchBox select[name="doctor"]').val();
    var date = $('.statisticsChartBox span.chartTitleData').html();
    // var result = {name: '', phone: '', time: date, status: '2', doctor_id: doctor_id, page: 1};
    var result = {name: '', phone: '', times: [date,date], status: '2', doctor_id: doctor_id, page: 1};
    var period = $(this).attr('data-time');
    if (period === 'am') {
        result.am = 1;
    } else if (period === 'pm') {
        result.am = 0;
    }
    getModalReservationMessage(result);
});
//医生统计 查看预约信息  end

//日历点击  start
$('#calendar').delegate('tbody tr td', 'click', function () {
    if (!($(this).hasClass('disabled'))) {
        var date = $(this).attr('data');
        date = date.substr(0, 4) + '-' + date.substr(4, 2) + '-' + date.substr(6, 2);
        getChartData(date);
    }
});
//日历点击  end

//根据日期 获取统计图表信息和上下午人数信息  start
function getChartData(date) {
    // ajaxGet(RESERVATIONCENTERURL.statistical.doctor.statistics, {time: date}, function (data) {
    ajaxGet(RESERVATIONCENTERURL.statistical.doctor.statistics, {time: date}, function (data) {
        if (data.code === 10000) {
            $('.statisticsChartBox span.chartTitleData').html(date);
            $('#statisticalNumber .morning span').html(((data.data.am / data.data.total) * 100).toFixed(0));
            $('#statisticalNumber .morningRightNumber p span').html(data.data.am);
            $('#statisticalNumber .afternoon span').html(((data.data.pm / data.data.total) * 100).toFixed(0));
            $('#statisticalNumber .afternoonRightNumber p span').html(data.data.pm);
            $('#statisticalNumber .allRightNumber p span').html(data.data.total);
            var xAxisData = [], seriesData = [];
            $.each(data.data.section, function (i, v) {
                xAxisData.push(i);
                seriesData.push(v);
            });
            statisticalChart('chartArea', xAxisData, seriesData);
            $('#reservationCenterNav li[data-page="statistical"]').attr('data-load', 'yes');//改变标签栏状态
        } else if (data.code === 40100) {
            aClick();
        } else if (String(data.code) === '40001') {
            $('.statisticsChartBox span.chartTitleData').html(date);
            $('#statisticalNumber .morning span').html(0);
            $('#statisticalNumber .morningRightNumber p span').html(0);
            $('#statisticalNumber .afternoon span').html(0);
            $('#statisticalNumber .afternoonRightNumber p span').html(0);
            $('#statisticalNumber .allRightNumber p span').html(0);
            $('#chartArea').html('<img src="../images/chartZero.png">');
        } else {
            alertModel('', '获取失败，' + data.message);
        }
    }, function () {
    });
};
//根据日期 获取统计图表信息和上下午人数信息  end


//***************************医生操作页面  end***************************


//***************************管理员操作页面  start***************************

//选择查看日期 输入框失去焦点 自动补齐另一个输入框并计算出表格日期  start
$('.adminStatistics .adminStatisticsDate .periodTime input').blur(function () {
    var _this = $(this);
    var siblingInput;
    setTimeout(function () {
        if (_this.val()) {
            if (_this.attr('name') === 'start_time') {
                siblingInput = _this.next().next();
                siblingInput.val(addDate(_this.val(), 6));
            } else {
                siblingInput = _this.prev().prev();
                siblingInput.val(addDate(_this.val(), -6));
            }
        }
    }, 150);
});
//选择查看日期 输入框失去焦点 自动补齐另一个输入框并计算出表格日期  end

//查询按钮 请求表格数据  start
$('#adminStatisticsSearchBtn').click(function () {
    var sTimeInput = $('.adminStatistics .adminStatisticsDate input[name="start_time"]');
    var eTimeInput = $('.adminStatistics .adminStatisticsDate input[name="end_time"]');
    if (!(sTimeInput.val()) || !(eTimeInput.val())) {
        sTimeInput.val(formatDate(new Date()));
        eTimeInput.val(addDate(formatDate(new Date()), 6));
    } else if ((sTimeInput.val()) && (eTimeInput.val())) {
        if (addDate(sTimeInput.val(), 6) != eTimeInput.val()) {
            eTimeInput.val(addDate(sTimeInput.val(), 6));
        }
    }
    var statisticsDataEl = $(this).parent().parent().find('.form-control');
    var result = {};
    for (var i = 0; i < statisticsDataEl.length; i++) {
        result[$(statisticsDataEl[i]).attr('name')] = $(statisticsDataEl[i]).val();
    }
    getVisitsStatistical(result);
});
//查询按钮 请求表格数据  end

// 根据查看日期 获取医生出诊情况统计  start
function getVisitsStatistical(result) {
    var statusArr = ['stop', 'normal', 'full', 'detonation'];
    ajaxGet(RESERVATIONCENTERURL.statistical.admin.visit, result, function (data) {
        if (data.code === 10000) {
            var str = '<thead><tr><th></th>', amStr = '', pmStr = '';
            $.each(data.data, function (i, v) {
                str += '<th>' + getWeek(i) + '<span>' + i + '</span></th>';
            });
            str += '</tr></thead> <tbody>';
            amStr += '<tr><td>上午</td>';
            pmStr += '<tr><td>下午</td>';

            $.each(data.data, function (I, V) {
                amStr += '<td><ul>';
                pmStr += '<td><ul>';
                $.each(V, function (s, w) {
                    for (var j = 0; j < w.length; j++) {
                        var pubStr = '<li class="' + statusArr[w[j].status.key] + '" data-doctorId="' + w[j].doctor_id + '" data-am="' + s + '" data-time="' + I + '">' +
                            '<span class="text" title="' + w[j].name + '">' + w[j].room + ' ' + w[j].name + '</span>' +
                            '<span class="status">' + w[j].status.value + '</span></li>';
                        if (s == 0) {
                            pmStr += pubStr;
                        } else if (s == 1) {
                            amStr += pubStr;
                        }
                    }
                });
                amStr += '</ul></td>';
                pmStr += '</ul></td>';
            });
            amStr += '</tr>';
            pmStr += '</tr>';
            str += amStr + pmStr + '</tbody>';
            $('#adminStatisticsTable').html(str);
        } else if (data.code === 40100) {
            aClick();
        } else {
            alertModel('', '获取失败，' + data.message);
        }
    }, function () {
    });
}

// 根据查看日期 获取医生出诊情况统计  end


//管理员统计 查看预约信息  start
$('#statistical').delegate('.adminStatistics-table tbody li', 'click', function () {
    if (!($(this).hasClass('stop'))) {
        $('#adminViewReservation').modal('show');
        var doctor_id = $(this).attr('data-doctorId');
        var am = $(this).attr('data-am');
        var date = $(this).attr('data-time');
        var result = {name: '', phone: '', times: [date, date], status: '2', doctor_id: doctor_id, am: am, page: 1};
        getModalReservationMessage(result);
    }
});
//管理员统计 查看预约信息  end


//***************************管理员操作页面  end***************************


//图表  start
function statisticalChart(chartId, xAxisData, seriesData) {
    Highcharts.chart(chartId, {
        credits: {
            enabled: false //不显示LOGO
        },
        chart: {
            type: 'column'
        },
        title: {
            text: ''  //上面标题
        },
        legend: {
            enabled: false    //下面中间标题
        },
        subtitle: {
            text: ''  //上面小标题
        },
        xAxis: {
            categories: xAxisData,
            lineColor: '#1ab394', //横轴颜色
            lineWidth: 2,
            tickColor: '#1ab394', //刻度颜色
            tickWidth: 2
        },
        yAxis: {
            labels: {
                x: -15
            },
            title: {
                text: '人数／人',
                style: {
                    color: '#1ab394'
                }
            },
            allowDecimals: false, //是否允许纵轴有小鼠
            lineColor: '#1ab394', //纵轴颜色
            lineWidth: 2
        },
        series: [{
            name: '人数',
            data: seriesData,
            color: '#1ab394',
            maxPointWidth: 50    //柱子最大宽度
        }],
        responsive: {
            rules: [{
                condition: {
                    maxWidth: 100
                },
                // Make the labels less space demanding on mobile
                chartOptions: {
                    xAxis: {
                        labels: {
                            formatter: function () {
                                return this.value.replace('月', '')
                            }
                        }
                    },
                    yAxis: {
                        labels: {
                            align: 'left',
                            x: 100,
                            y: -2
                        },
                        title: {
                            text: ''
                        }
                    }
                }
            }]
        }
    });
};
//图表  end

//统计  查看预约信息弹出框  获取数据方法  和  字符串拼接  start
function getModalReservationMessage(result) {
    $.get(RESERVATIONCENTERURL.reservationList.index, result, function (data) {
        if (data.code === 10000) {
            $('#adminViewReservation .modal-body .tableArea').html(reservationMessageStr(data.data));
            // 页码
            if (data.meta.pagination.total_pages > 1) {
                page('listPager', data.meta, getModalReservationMessage, result);
            } else {
                $('#messageModalPager').html('');
            }
        } else if (data.code === 40100) {
            aClick();
        }
        else if (String(data.code) === '40001') {
            $('#adminViewReservation .modal-body .tableArea').html(reservationMessageStr(data.data));
            // 页码
            $('#messageModalPager').html('');
        }
    });
}

function reservationMessageStr(data) {
    var str = '<table class="table-bordered table-hover text-center reservationCenter-table modalViewReservation-table"><thead><tr><th>序号</th><th>姓名</th><th>性别</th><th>年龄</th><th>手机号</th><th>预约时间</th></tr></thead><tbody>';
    if (data && data.length) {
        $.each(data, function (i, v) {
            str += '<tr><td>' + (i + 1) + '</td><td>' + v.patient.name + '</td>' +
                '<td>' + v.patient.sex.value + '</td><td>' + v.patient.age + '</td>' +
                '<td>' + v.patient.phone + '</td>' +
                '<td>' + v.time + ' ' + v.section + '</td></tr>';
        });
    } else {
        str += '<tr><td colspan="6">暂无数据</td></tr>';
    }
    str += '</tbody></table>';
    return str;
};
//统计  查看预约信息弹出框  获取数据方法  和  字符串拼接  end
//查询按钮点击 请求患者池列表数据  start
$('#patientPoolSearchBtn').click(function () {
    var params = getSearchParams($(this));
    if (params) {
        getpatientPoolList(params);
    }
});
//查询按钮点击 请求患者池列表数据  end

//患者池列表 获取数据 方法  start
function getpatientPoolList(result) {
    ajaxGet(RESERVATIONCENTERURL.patientPool.doctor.index, result, function (data) {
        var is_reception = {
            false: '否',
            true: '是'
        };
        if (data.code === 10000) {
            var str = '';
            if ($('#side-menu strong.font-bold').attr('data-doctor')) {
                $.each(data.data, function (i, v) {
                    str += '<tr data-reservationId="' + v.id + '"><td><lable>' +
                        '<input type="checkbox" class="checkBox">' + (i + 1) + '</lable></td>' +
                        '<td>' + v.name + '</td><td>' + v.sex.value + '</td><td>' + v.age + '</td>' +
                        '<td>' + v.phone + '</td><td>' + v.reservation_date + ' ' + v.reservation_time.reservation_start + '-' + v.reservation_time.reservation_end + '</td>' +
                        '<td>' + is_reception[v.is_reception] + '</td><td>' +
                        '<button type="button" class="btn btn-warning btn-outline margin-right-5 viewCase" data-patient-id="' + data.data[i].patient_id + '">查看病历</button>' +
                        '<button type="button" class="btn btn-danger btn-outline margin-right-5 refused">拒绝</button>' +
                        '<button type="button" class="btn btn-primary btn-outline margin-right-5 accept">接受</button></td></tr>';
                });
            } else {
                $.each(data.data, function (i, v) {
                    str += '<tr data-reservationId="' + v.id + '" data-reservationTime="' + v.reservation_date + '"><td><lable>' +
                        '<input type="checkbox" class="checkBox">' + (i + 1) + '</lable></td>' +
                        '<td>' + v.name + '</td><td>' + v.sex.value + '</td><td>' + v.age + '</td><td>' + v.phone + '</td>' +
                        '<td>' + v.reservation_date + ' ' + v.reservation_time.reservation_start + '-' + v.reservation_time.reservation_end + '</td>' +
                        '<td><button type="button" class="btn btn-primary btn-outline margin-right-5 allotment">分配</button></td></tr>';
                });
            }
            $('#patientPoolListBody').html(str);
            // 页码
            if (data.meta.pagination.total_pages > 1) {
                page('patientPoolPager', data.meta, getpatientPoolList, result);
            } else {
                $('#patientPoolPager').html('');
            }
            $('#reservationCenterNav li[data-page="patientPool"]').attr('data-load', 'yes');//改变标签栏状态
        } else if (data.code === 40100) {
            aClick();
        } else if (String(data.code) === '40001') {
            $('#patientPoolListBody').html('<tr><td colspan="8">暂无数据</td></tr>');
            $('#patientPoolPager').html('');
        } else {
            alertModel('', '获取失败，请重试！');
        }
    }, function (x, t, e) {
    })
};
//患者池列表 获取数据 方法  end

//查看病历按钮  点击 start
$('#patientPoolListBody').delegate('td button.viewCase', 'click', function () {
    var id = $(this).attr('data-patient-id');

    $.get('/manage/record/list/' + id, function (data) {
        if (data.code) {
            aClick();
        } else {
            var str = '';
            $.each(data, function (i, v) {
                str += '<option value="' + v.id + '">' + v.visit_type.value + v.clinic_at + '</option>';
            });
            $('#witch_record').html(str).change();
            $('#viewCaseModal').modal('show');
        }

    }, 'json');
})

//分配  模态框 选择医生  请求能分配的医生放入框内  start
function assignedDoctor() {
    var reservationIdArr = $('#selectDistributionSaveBtn').attr('data-reservationIdArr').split(',');
    reservationIdArr = parseInt(reservationIdArr[0]);
    $.get(RESERVATIONCENTERURL.patientPool.admin.doctors, {id: reservationIdArr}, function (data) {
        if (data.code == 10000) {
            var str = '';
            var status = {
                0: {className: 'stop', disabled: true},
                1: {className: 'normal', disabled: false},
                2: {className: 'full', disabled: false},
                3: {className: 'detonation', disabled: true}
            };
            var V = data.data;
            for (var j = 0; j < V.length; j++) {
                str += '<label class="' + status[V[j].status.key].className + '">';
                if (status[V[j].status.key].disabled) {
                    str += '<input type="radio" name="distributionName" value="' + V[j].doctor_id + '" disabled>';
                } else {
                    str += '<input type="radio" name="distributionName" value="' + V[j].doctor_id + '">';
                }
                str += '<span class="text" title="' + V[j].name + '">' + V[j].room + ' ' + V[j].name + '</span>' +
                    '<span class="status">' + V[j].status.value + '</span></label>';
            }
            $('#selectDistribution div.selectDoctorBox').html(str);
        } else if (data.code === 40100) {
            aClick();
        } else {
            $('#selectDistributionSaveBtn').prev().click();  //关闭模态框
            alertModel('', '获取可分配的医生获取失败！');
        }
    });
};
//分配  模态框 选择医生  请求能分配的医生放入框内  end
//管理员  一键随机分配  和选择分配  和  操作栏分配按钮   start
$('#randomlyAssignedBtn').click(function () {
    var reservationIdArr = getReservationId('patientPoolListBody');
    if (reservationIdArr.length) {
        confirmModel('', '确定要一键随机分配吗？', '', '', function () {
            ajaxPost('', {ids: reservationIdArr}, function (data) {
                if (data.code == 10000) {
                    $('#patientPoolSearchBtn').click();
                    alertModel('', '随机分配成功！');
                } else if (data.code === 40100) {
                    aClick();
                } else {
                    alertModel('', '随机分配失败，请重试！');
                }
            }, function () {
            })
        });
    } else {
        alertModel('', '请先选择患者！');
    }
});
$('#selectDistributionBtn').click(function () {
    var reservationIdArr = getReservationId('patientPoolListBody');
    if (reservationIdArr.length) {
        for (var i = 1; i < reservationIdArr.length; i++) {
            if ($('#patientPoolListBody tr[data-reservationid="' + reservationIdArr[0] + '"]').attr('data-reservationTime') != $('#patientPoolListBody tr[data-reservationid="' + reservationIdArr[i] + '"]').attr('data-reservationTime')) {
                alertModel('', '批量分配只能选择预约时间为同一天！');
                return false;
            }
        }
        $('#selectDistribution').modal('show');  //打开修改诊室模态框
        $('#selectDistributionSaveBtn').attr('data-reservationIdArr', reservationIdArr);
        $('#selectDistributionSaveBtn').attr('data-tableId', 'patientPoolListBody');
        assignedDoctor();
    } else {
        alertModel('', '请先选择患者！');
    }
});
$('#patientPoolListBody').on('click', '.allotment', function () {
    var reservationIdArr = new Array($(this).parent().parent().attr('data-reservationid'));
    $('#selectDistribution').modal('show');  //打开修改诊室模态框
    $('#selectDistributionSaveBtn').attr('data-reservationIdArr', reservationIdArr);
    $('#selectDistributionSaveBtn').attr('data-tableId', 'patientPoolListBody');
    assignedDoctor();
});
//管理员  一键随机分配  和选择分配  和  操作栏分配按钮   end

//管理员 选择医生分配  弹出框  确认按钮   start
$('#selectDistributionSaveBtn').click(function () {
    var reservationIdArr = $(this).attr('data-reservationIdArr').split(',');
    for (var j = 0; j < reservationIdArr.length; j++) {
        reservationIdArr[j] = parseInt(reservationIdArr[j]);
    }
    var doctorIdInput = $(this).parent().prev().find('.selectDoctorBox input');
    var doctor_id;  //存储选择的医生的ID
    for (var j = 0; j < doctorIdInput.length; j++) {
        if ($(doctorIdInput[j]).is(':checked')) {
            doctor_id = $(doctorIdInput[j]).val();
        }
    }
    var result = {ids: reservationIdArr, doctor_id: doctor_id};
    //todo 发信息部分  start
    // var sendMessageInput=$(this).parent().prev().find('.sendMessageType input');
    // result.send_message=[];
    // for(var m=0;m<sendMessageInput.length;m++){
    //     if($(sendMessageInput[m]).is(':checked')){
    //         result.send_message.push($(sendMessageInput[m]).val());
    //     }
    // }
    //todo 发信息部分  end
    $(this).prev().click();  //关闭模态框
    ajaxPost(RESERVATIONCENTERURL.patientPool.admin.assignTo, result, function (data) {
        if (data.code == 10000) {
            $('#patientPoolSearchBtn').click();
            alertModel('', '分配成功！');
        } else if (data.code === 40100) {
            aClick();
        } else {
            alertModel('', '分配失败，请重试！');
        }
    }, function () {
    });
});
//管理员 选择医生分配  弹出框  确认按钮   end


//用户  批量接受和拒绝   start
$('#doctorAcceptBtn').click(function () {
    var reservationIdArr = getReservationId('patientPoolListBody');
    if (reservationIdArr.length) {
        acceptRefused(RESERVATIONCENTERURL.patientPool.doctor.accept, '接受', reservationIdArr, 'click');
    } else {
        alertModel('', '请先选择患者！');
    }
});
$('#doctorRefusedBtn').click(function () {
    var reservationIdArr = getReservationId('patientPoolListBody');
    if (reservationIdArr.length) {
        acceptRefused(RESERVATIONCENTERURL.patientPool.doctor.reject, '拒绝', reservationIdArr, 'click');
    } else {
        alertModel('', '请先选择患者！');
    }
});
//用户  批量接受和拒绝   end
//用户  单个接受和拒绝   start
$('#patientPoolListBody').delegate('td button.accept', 'click', function () {
    var reservationId = new Array($(this).parent().parent().attr('data-reservationId'));
    acceptRefused(RESERVATIONCENTERURL.patientPool.doctor.accept, '接受', reservationId, $(this));
});
$('#patientPoolListBody').delegate('td button.refused', 'click', function () {
    var reservationId = new Array($(this).parent().parent().attr('data-reservationId'));
    acceptRefused(RESERVATIONCENTERURL.patientPool.doctor.reject, '拒绝', reservationId, $(this));
});
//用户  单个接受和拒绝   end

//接受 和  拒绝  方法  start
function acceptRefused(url, text, ids, status) {
    confirmModel('', '确定要' + text + '吗？', '', '', function () {
        ajaxPost(url, {ids: ids}, function (data) {
            if (data.code == 10000) {
                $('#patientPoolSearchBtn').click();
                alertModel('', text + '成功！');
            } else if (data.code === 40100) {
                aClick();
            } else {
                alertModel('', text + '失败，请重试！');
            }
        }, function () {
        })
    });
};
//接受 和  拒绝  方法  end
//查询按钮 点击  start
$('#messageCenterSearchBtn').click(function () {
    var start_time = $('#messageCenter .periodTime input[name="start_time"]').val();
    var end_time = $('#messageCenter .periodTime input[name="end_time"]').val();
    var result = {page: 1};
    if (start_time && end_time) {
        if (checkTwoDate(start_time, end_time)) {
            result['start_time'] = start_time;
            result['end_time'] = end_time;
        } else {
            alertModel('', '开始时间要早于结束时间！');
            return false;
        }
    } else if (start_time) {
        result['start_time'] = start_time;
    } else if (end_time) {
        result['end_time'] = end_time;
    }
    getMessageList(result);
});
//查询按钮 点击  end

//信息中心  获取消息列表方法  start
function getMessageList(result) {
    ajaxGet(RESERVATIONCENTERURL.messageCenter.index, result, function (data) {
        if (data.code === 10000) {
            var str = '';
            for (var i = 0; i < data.data.length; i++) {
                str += '<tr><td><span>' + data.data[i].source + '：</span>' + data.data[i].message + '</td>' +
                    '<td class="text-right text-muted">' + data.data[i].created_at + '</td></tr>';
            }
            $('#messageListBody').html(str);
            // 页码
            if (data.meta.pagination.total_pages > 1) {
                page('messageCenterPager', data.meta, getMessageList, result);
            } else {
                $('#messageCenterPager').html('');
            }
        } else if (data.code === 40100) {
            aClick();
        } else if (String(data.code) === '40001') {
            $('#messageCenterPager').html('');
            $('#messageListBody').html('<tr class="text-center"><td>暂无数据</td></tr>');
        } else {
            alertModel('', '获取失败，请重试！');
        }
    }, function () {
    });
}

//信息中心  获取消息列表方法  end

//信息中心  有消息时 圆圈标红显示   start
function getMessageNum() {
    $.get(RESERVATIONCENTERURL.messageCenter.unread, function (data) {
        if (data.code == 10000) {
            var num = parseInt($('#reservationCenterNav li[data-page="messageCenter"] b').attr('data-num'));
            num += parseInt(data.data.count);
            $('#reservationCenterNav li[data-page="messageCenter"] b').attr('data-num', num);
        } else if (data.code === 40100) {
            aClick();
        }
    });
}

getMessageNum();
setInterval(function () {
    getMessageNum();
}, 30000);
//信息中心  有消息时 圆圈标红显示   end
// 标签添加点击事件  存储session 用于刷新页面时定位到标签页    点击导航列表预约中心  清除存储的session

//标签点击  start
$('#reservationCenterNav li').click(function () {
    var pageType = $(this).attr('data-page');
    sessionStorage.setItem('reservationCenterTabPage', pageType);
    if ($(this).attr('data-load') === 'no') {
        getPageData(pageType);
    }
});
//标签点击  end

//页面加载时候获取session请求对应数据  start
var F5Page = sessionStorage.getItem('reservationCenterTabPage');
if (F5Page) {
    getPageData(F5Page);
    var currentLi = $('#reservationCenterNav li[data-page="' + F5Page + '"]');
    if (!(currentLi.hasClass('active'))) {
        currentLi.addClass('active');
        $('#reservationCenterNav li:first-child').removeClass('active');
        $(currentLi.find('a').attr('href')).addClass('active').parent().find('>div:first-child').removeClass('active');
    }
} else {
    $('#listQueryBtn').click();
}

//页面加载时候获取session请求对应数据  end


function getPageData(pageType) {
    if (pageType === 'reservationList') {
        $('#listQueryBtn').click();
    } else if (pageType === 'statistical') {
        if ($('#side-menu li.nav-header strong.font-bold').attr('data-doctor')) {   //医生用户
            var date = formatDate(new Date());
            $('.statisticsChartBox span.chartTitleData').html(date);
            getChartData(date);
        } else {                                                                    //管理员用户
            $('#adminStatisticsSearchBtn').click();
        }
    } else if (pageType === 'patientPool') {
        $('#patientPoolSearchBtn').click();
    } else if (pageType === 'messageCenter') {
        $('#reservationCenterNav li[data-page="messageCenter"] b').html('');
        $('#reservationCenterNav li[data-page="messageCenter"] b').attr('data-num', '0');
        $('#messageCenterSearchBtn').click();
    }
}

//退出跳转
function aClick() {
    //跳转
    window.location.pathname = "/manage/auth/logout";
    //清除缓存
    sessionStorage.clear();
    localStorage.clear();
};


